<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class HealthDrinkController extends ApiController
{

    /**
     * 获取用户喝水记录
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $user = Auth::user();
        $user_id = $user->id;
        $diary_id = $request->input("id", 0);
        if (empty($diary_id)) {
            return $this->failed("参数错误");
        }
        $health_diary = DB::table('user_health_diary')->select('id', 'drink_count', 'date')->where(['id' => $diary_id, 'user_id' => $user_id])->first();
        if(empty($health_diary)) {
            return $this->failed("参数错误");
        }

        $cup_ids = DB::table('user_health_drink AS d')->where(['diary_id' => $diary_id])->value('cup_ids');

        $cup_ids = empty($cup_ids) ? [] : json_decode($cup_ids);
        return $this->success(['health_diary' => $health_diary, 'cup_ids' => $cup_ids]);
    }

    /**
     * 喝水记录
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
   public function editHealthDrink(Request $request)
   {
       $user = Auth::user();
       $user_id = $user->id;
       $diary_id = $request->input("diary_id", 0);
       $cup_ids = $request->input("cup_ids", "");
       if (empty($cup_ids)) {
           $cup_ids = [];
       }
       if(!is_array($cup_ids)) {
           return $this->failed("参数错误");
       }
       if (empty($diary_id)) {
           return $this->failed("参数错误");
       }
       $health_diary = DB::table('user_health_diary')->select('id', 'sport_caloric')->where(['id' => $diary_id, 'user_id' => $user_id])->first();
       if(empty($health_diary)) {
           return $this->failed("参数错误");
       }

       $drink_count = count($cup_ids);

       DB::beginTransaction(); //开启事务

       $health_drink = DB::table('user_health_drink')->where(['diary_id' => $diary_id])->first();
       if (empty($health_drink)) {
           $drink_res = DB::table('user_health_drink')->insert([
               'diary_id' => $diary_id,
               'user_id' => $user_id,
               'cup_ids' => json_encode($cup_ids)
           ]);
       } else {
           $drink_res = DB::table('user_health_drink')->where('id', $health_drink->id)->update(['cup_ids' => json_encode($cup_ids)]);
       }

       $diary_res = DB::table('user_health_diary')->where('id', $diary_id)->update(['drink_count' => $drink_count]);

       if ($drink_res === false || $diary_res === false) {
           DB::rollBack(); //回滚事务
           return $this->failed("记录喝水失败");
       }
       DB::commit(); //提交事务
       return $this->success("记录喝水成功");
   }
}
